package com.fingard.dsp.bank.directbank.swiftpass01;

import java.io.BufferedReader;
import java.io.StringReader;
import java.util.HashMap;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.bankInterface.IStatement;
import com.fingard.dsp.bank.reqrespobj.statement.ReqQryStatement;
import com.fingard.dsp.bank.reqrespobj.statement.RetAtsStatement;
import com.fingard.dsp.bank.reqrespobj.statement.TransState;
import com.fingard.dsp.bank.reqrespobj.statement.detail.RetAtsStatementDetail;
import com.fingard.text.SplitHelper;
import com.fingard.text.StringHelper;

public class SwiftPass01Statement extends SwiftPass01Base implements IStatement {
	public RetAtsStatement d_Qry_Statement(ReqQryStatement p_reqQrySttm) {
		RetAtsStatement retAts = new RetAtsStatement(p_reqQrySttm);
		retAts.writeStart();
		
		String tmpRespCode = "";
		String tmpRespInfo = "";
		
		try {
			ActSetItem actItem = this.getBankConfig().getActSetItemByAny(p_reqQrySttm.actNum, "", "", "*");
			if (actItem == null) {
				tmpRespCode = "-1";
				tmpRespInfo = "未找到账号[" + p_reqQrySttm.actNum + "]商户配置信息";
			} else {
				HashMap<String, String> mapParams = new HashMap<String, String>();
				
				mapParams.put("service", "pay.bill.merchant");
				mapParams.put("version", "1.0");
				mapParams.put("charset", getCharset());
				mapParams.put("sign_type", "MD5");

				String mch_id = actItem.merchantId;
				mapParams.put("mch_id", mch_id);

				mapParams.put("bill_date",Format.Date8Format.format(p_reqQrySttm.getBusDate()));
				String bill_type = getBankConfig().getValueAsString("bill_type");
				if (StringHelper.isNullOrEmpty(bill_type)) {
					bill_type = "ALL";
				}
				mapParams.put("bill_type", bill_type);

				String nonce_str = get_nonce_str();
				mapParams.put("nonce_str", nonce_str);
				String signMsg = signMessage(mapParams, actItem.saltKey);
				mapParams.put("sign", signMsg);

				String tmpXml = buildXml(mapParams);

				String[] tmpStrRet = sendToBank(tmpXml, "downloadbill");// 发送
				if (tmpStrRet[0].length() == 0) {
					// {"status":"400","message":"商户不存在"}
					if (tmpStrRet[1].startsWith("{")) {
						String status = "";
						String message = "";
						String[] tmpMsgs = tmpStrRet[1].split(",");
						for (int i = 0; i < tmpMsgs.length; i++) {
							String[] values = tmpMsgs[i].split(":");
							if (values.length > 1) {
								if (values[0].indexOf("status") >= 0|| values[0].indexOf("result") >= 0) {
									status = values[1].replace("\"", "").replace("{", "").replace("}", "");
								} else if (values[0].indexOf("message") >= 0) {
									message = values[1].replace("\"", "").replace("{", "").replace("}", "");
								}
							}
						}
						tmpRespCode = "-1";
						tmpRespInfo = StringHelper.joinNotEmpty("-", status,message);
						if (StringHelper.isNullOrEmpty(tmpRespInfo)) {
							tmpRespInfo = tmpStrRet[1];
						}
					} else {// 有数据
						int indexTotal = tmpStrRet[1].indexOf("总交易单数");
						if (indexTotal >= 0) {
							String lineTotal = tmpStrRet[1]
									.substring(indexTotal);
							String[] lines = lineTotal.split("\n");
							if (lines.length > 1) {
								HashMap<String, String> mapTotal = SplitHelper.splitAsValueMap(lines[0].trim(),	lines[1].trim(), ",");
								if (mapTotal.containsKey("总交易单数")) {
									retAts.totalNum = mapTotal.get("总交易单数").replace("`", "");
									tmpRespCode = "0";
								} else {
									tmpRespCode = "-1";
									tmpRespInfo = "无总交易单数列";
								}
							} else {
								tmpRespCode = "-1";
								tmpRespInfo = "文件结尾结构不符合预期";
							}
						} else {
							tmpRespCode = "-1";
							tmpRespInfo = "返回内容无总交易单数";
						}
						if (tmpRespCode.equals("0")) {
							StringReader strReader = new StringReader(tmpStrRet[1]);
							BufferedReader tmpReader = new BufferedReader(strReader);

							int int1 = 65279;
							// char char1 = (char)int1;
							// String headChar = "" + char1;
							String line1 = tmpReader.readLine();
							int idxHdChar = line1.indexOf(int1);
							if (idxHdChar >= 0) {
								line1 = line1.substring(idxHdChar + 1);
							}
							String[] columns = line1.split(",");
							while (true) {
								String eachline = tmpReader.readLine();
								if (eachline == null) {
									break;
								}
								String[] values = eachline.split(",");
								if (columns.length == values.length) {
									HashMap<String, String> mapKV = SplitHelper
											.splitAsValueMap(columns, values);
									RetAtsStatementDetail retDetail = new RetAtsStatementDetail();

									if (mapKV.containsKey("总金额")) {
										retDetail.amount = mapKV.get("总金额").replace("`", "");
									}
									if (mapKV.containsKey("?交易时间")) {
										retDetail.busTime = mapKV.get("?交易时间").replace("`", "").replace("-", "").replace(":", "").replace(" ", "");
									}
									if (mapKV.containsKey("商户订单号")) {
										retDetail.askNumber = mapKV.get("商户订单号").replace("`", "");
									}
									if (mapKV.containsKey("交易状态")) {
										if (mapKV.get("交易状态").replace("`", "").equals("支付成功")) {
											retDetail.transState = TransState.Success;
										} else if (mapKV.get("交易状态")	.replace("`", "").equals("转入退款")) {
											retDetail.transState = TransState.ToRefund;
										} else {
											retDetail.transState = TransState.Exception;
										}
									}
									if (mapKV.containsKey("付款银行")) {
										retDetail.oppBank = mapKV.get("付款银行")
												.replace("`", "");
									}
									if (mapKV.containsKey("手续费")) {
										retDetail.fee = mapKV.get("手续费")
												.replace("`", "");
									}
									if (mapKV.containsKey("货币种类")) {
										retDetail.cur = convertCurToATS(mapKV
												.get("货币种类").replace("`", ""));
									}
									if (mapKV.containsKey("威富通订单号")) {
										retDetail.bkSeq = mapKV.get("威富通订单号")
												.replace("`", "");
									}

									retAts.writeRetDetail(retDetail);
								} else {
									break;
								}
							}
							retAts.isWritedTotalNum(retAts.totalNum);
						}
					}
				} else {
					tmpRespCode = "-1";
					tmpRespInfo = tmpStrRet[1];
				}
			}
			
			if (tmpRespCode.equals("-1")) {
				retAts.writeRespCode(tmpRespCode);
				retAts.writeRespInfo(tmpRespInfo);
			} else if (retAts.getWrittenRdCount() == 0) {
				retAts.writeRespCode("0");
				if (StringHelper.isNullOrEmpty(tmpRespInfo)) {
					tmpRespInfo = "交易为空";
				}
				retAts.writeRespInfo(tmpRespInfo);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			tmpRespCode = "-1";
			tmpRespInfo = ex.getMessage();
			this.WriteBankLogLn(ex);
		}

		retAts.writeEnd();
		return retAts;
	}
}
